package manager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import entity.Course;

/**
 * An utility class to execute read queries, handle result sets and obtain
 * results in the desired entity object type.
 * 
 * @author
 * 
 */
class RetrieveCourseUtil {

	/**
	 * Convenient method to retrieve multiple courses from database for the
	 * given query.
	 * 
	 * @param dbMgr
	 *            database manager object on which the query should be executed
	 * @param sql
	 *            the SQL statement to execute
	 * @param param
	 *            sequence of parameters to be used in the SQL statement
	 * @return an ArrayList of course objects with information retrieved from
	 *         the database
	 */
	static ArrayList<Course> retrieveMultipleCoursesForQuery(DatabaseMgr dbMgr,
			String sql, Object... param) {
		ArrayList<Course> courses = new ArrayList<Course>();

		try {
			ResultSet rs = dbMgr.openAndRead(sql, param);
			while (rs.next()) {
				courses.add(newCourseFromResultSet(rs));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return courses;
	}

	/**
	 * Convenient method to retrieve a single course from database for the given
	 * query.
	 * 
	 * @param dbMgr
	 *            database manager object on which the query should be executed
	 * @param sql
	 *            the SQL statement to execute
	 * @param param
	 *            sequence of parameters to be used in the SQL statement
	 * @return a new course object with information retrieved from the database
	 */
	static Course retrieveCourseForQuery(DatabaseMgr dbMgr, String sql,
			Object... param) {
		Course course = null;
		try {
			ResultSet rs = dbMgr.openAndRead(sql, param);
			while (rs.next()) {
				course = newCourseFromResultSet(rs);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return course;
	}

	/**
	 * Convenient method to create new course object from the given result set.
	 * 
	 * @param rs
	 *            result set containing course information
	 * @return a new course object with information extracted from the result
	 *         set
	 * @throws SQLException
	 */
	private static Course newCourseFromResultSet(ResultSet rs)
			throws SQLException {
		return new Course(rs.getString("courseCode"), rs.getString("title"),
				rs.getString("description"), rs.getString("school"),
				rs.getString("examDate"), rs.getString("examStartTime"),
				rs.getString("examEndTime"));
	}
}
